package com.rabbit.rebbitmqextension.condtroller;


import com.rabbit.rebbitmqextension.constant.Constants;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@RequestMapping("/produce")
public class ProduceController {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Resource(name = "confirmRabbitTemplate")
    private RabbitTemplate confirmRabbitTemplate;

    @RequestMapping("noneAck")
    public String noneAck() {
        rabbitTemplate.convertAndSend("", Constants.NONE_QUEUE,"hello , I try noneAck");
        return "消息发送成功： noneAck";
    }

    @RequestMapping("autoAck")
    public String autoAck() {
        rabbitTemplate.convertAndSend("", Constants.AUTO_QUEUE,"hello , I try autoAck");
        return "消息发送成功： autoAck";
    }

    @RequestMapping("manualAck")
    public String manualAck() {
        rabbitTemplate.convertAndSend("", Constants.MANUAL_QUEUE,"hello , I try manualAck");
        return "消息发送成功： manualAck";
    }


    @RequestMapping("/confirm")
    public String confirm() {
        CorrelationData correlationData= new CorrelationData();

        // 当我们 每次调用 这个 方法的时候，rabbitTemplate 都会重新进行设置一次，就会报错：
        //  Only one ConfirmCallback is supported by each RabbitTemplate
/*        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack){
                    System.out.printf("消息接收成功, id:%s \n", correlationData.getId());
                }else{
                    System.out.printf("消息接收失败, id:%s, cause: %s", correlationData.getId(), cause);
                }
            }
        });*/
        confirmRabbitTemplate.convertAndSend("", Constants.CONFIRM_QUEUE,"hello , I try confirm",correlationData);
        return " 消息发送成功： confirm ";
    }

    @RequestMapping("/returnQ")
    public String returnQ() {
        CorrelationData correlationData= new CorrelationData();

        confirmRabbitTemplate.convertAndSend(Constants.RETURN_EXCHANGE, "return_queue1","hello , I try returnQ",correlationData);
        return " 消息发送成功： returnQ ";
    }
}
